<?php

namespace App\Console\Commands\Purchase;

use App\Models\Purchase\PurchaseOrderProcess;
use App\Models\Purchase\PurchasePreSettleOrder;
use App\Models\Purchase\PurchasePreSettleOrderSub;
use App\Models\Steel\SteelArchive;
use App\Models\Stock\Stock;
use App\Services\Purchase\PurchaseCommon;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Log;

class ChangePreSettlePrice extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'command:changepresettleprice';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '自动重新计价';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        //获取需要重新计价的列表
        $this->dosettleprice();
        //根据列表获取对应价格
        Log::info('自动重新计价日期'.date('Y-m-d H:i:s'));
        return 0;
    }


    //重新计价
    protected function dosettleprice(){
        $list=PurchasePreSettleOrder::getSettlePriceOrderList();
        foreach($list as $info){
            $finishcount=PurchaseOrderProcess::where(['order_id' => $info['order_id'], 'is_del' => 1,'is_finish'=>2])->count();
            if($finishcount>0){//主订单已完结，不可计价
               continue;
            }
            $cpid=$info['cpid'];
            $order_id=$info['id'];

            foreach($info['suborder'] as $suborder){
                $stockinfo = Stock::where('id', $suborder['stock_id'])->first()->toArray();
                $steel_archive_info = SteelArchive::where('id', $stockinfo['steel_archive_id'])->first()->toArray();
                $baseprice=PurchaseCommon::getsettleprice($cpid,$steel_archive_info['steel_factory_id'],$info['settle_model_start_time'], $info['settle_model_end_time']);
                if($baseprice<=0){//取不到价格跳过
                    continue;
                }
                $price=mathfuncmoney('add',$baseprice,$suborder['add_price']);
                $data=[
                    'price'=>$price,
                    'total_money'=>mathfuncmoney('mul',mathfuncweight('div',$suborder['total_weight'],1000,4),$price,0)
                ];
                PurchasePreSettleOrderSub::where(['id'=>$suborder['id'],'pre_settle_order_id'=>$order_id,'is_del'=>1])->update($data);
            }

        }



    } 
}
